//
//  CXBaseService.m
//  Codex
//
//  Created by ChenJie on 01/02/2018.
//  Copyright © 2018 Mist. All rights reserved.
//

#import <MJExtension/MJExtension.h>
#import "CXBaseService.h"

@implementation CXBaseService

/**
 * pack requestParameters and parse response
 */
- (NSURLSessionDataTask *)post:(NSString *)url
                    parameters:(NSDictionary *)requestParameters
                       success:(WebDriverSuccessCallback)success
                       failure:(WebDriverFailureCallback)failure {
    
    // pack parameters, including baseParameters and requestParameters
    NSMutableDictionary *packedParameters = [NSMutableDictionary dictionaryWithDictionary:[self baseParameters]];
    [packedParameters addEntriesFromDictionary:requestParameters];
    
    return [self post:url parameters:packedParameters progress:^(NSProgress *progress) {
       // do something
    } success:^(id response) {
        NSDictionary *responseObject = [self parsedResponse:response];
        !success ?: success(responseObject);
    } failure:^(NSError *error) {
        !failure ?: failure(error);
    }];
}


/**
 * just send post request
 */
- (NSURLSessionDataTask *)post:(NSString *)url
                    parameters:(NSDictionary *)parameters
                      progress:(WebDriverProgressCallback)progress
                       success:(WebDriverSuccessCallback)success
                       failure:(WebDriverFailureCallback)failure {
    
    return [[CXWebDriver sharedDriver] post:url parameters:[self packedParameters:parameters] progress:^(NSProgress *postProgress) {
        !progress ?: progress(postProgress);
    } success:^(id response) {
        !success ?: success(response);
    } failure:^(NSError *error) {
        !failure ?: failure(error);
    }];
}

- (NSDictionary *)parsedResponse:(NSData *)responseData {
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSScanner *theScanner = [NSScanner scannerWithString:responseString];
    NSString *text = nil;
    while ([theScanner isAtEnd] == NO) {
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        [theScanner scanUpToString:@">" intoString:&text] ;
        responseString = [responseString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return [responseString mj_JSONObject];
}

- (NSDictionary *)packedParameters:(NSDictionary *)original {
    return @{@"jsonRequest": [original mj_JSONString]};
}

- (NSDictionary *)baseParameters {
    return @{
             @"appVer": @"3.1.99.094",
             @"deviceId": @"18071adc033b205bd3b",
             @"deviceToken": @"18071adc033b205bd3b",
             @"sysType": @"I",
             };
}

@end
